<template>
  <a-select
    :allow-search="true"
    placeholder="未选择"
    style="width: 100%"
    label-in-value
    :mode="mode"
    v-model="val"
    :loading="fetching"
    :disabled="disabled"
    @focus="handleFocus"
    @search="handleSearch"
    @change="handleChange"
  >
    <a-option v-for="d in data" :key="d.value" :value="d.value" :label="d.text">{{ d.text }}</a-option>
    <template #empty>
      <a-spin v-if="fetching" size="small" />
      <span v-else>无数据</span>
    </template>
  </a-select>
</template>
<script>
import debounce from 'lodash/debounce'
import _ from 'lodash'

export default {
  name: 'PullSelect',
  props: {
    mode: {
      type: String,
      default: 'default'
    },
    // 请求携带参数
    query: {
      type: Object,
      default: function () {
        return {}
      }
    },
    apiUrl: {
      type: String,
      default: '/product/category/productInfo'
    },
    value: {
      type: [Object, Array],
      default: function () {
        return {}
      }
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data () {
    this.handleSearch = debounce(this.handleSearch, 800)
    const val = Array.isArray(this.value) ? this.value || [] : this.value || {}
    return {
      data: [],
      val,
      firstFocus: true,
      fetching: false
    }
  },
  watch: {
    value: {
      handler (val) {
        this.val = _.cloneDeep(val)
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    handleFocus () {
      this.firstFocus && this.handleSearch('')
      this.firstFocus = false
    },
    async handleSearch (value) {
      const _this = this
      this.data = []
      this.fetching = true
      try {
        // TODO: 请求参数
        const queryParamrter = Object.assign({}, this.query, {
          name: value
        })
        const { result } = await _this.$http.get(_this.apiUrl, {params:queryParamrter})
        const resultData = result.map(arg => ({
          text: arg.value,
          value: arg.key
        }))
        this.data = resultData
        this.fetching = false
      } catch (error) {
        console.log('pullSelect-error:', error)
      }
    },
    handleChange (val) {
      console.log('改变change：', val)
      Object.assign(this, {
        // val,
        fetching: false
      })
      this.$emit('change', val)
    }
  }
}
</script>
